import { nextTick, onMounted, reactive, ref } from 'vue'
import {
  getRoleListApi,
  getRoleIdApi,
  assingRoleSaveApi
} from '@/api/user/user'
import { AssignRoleListParm } from '@/api/user/UserModel'
import { getUserId } from '@/utils/auth'
import useInstance from '@/hooks/useInstance'
export default function useAssignRole (dialog, onClose, onShow) {
  const { global } = useInstance()
  // 表格高度
  const tableHeight = ref(0)
  //被分配角色的用户id，是用户自己的id
  const selecUserId = ref<string | number>('')
  //选择的角色的id，比如管理员的id是1，用户的id是2，这里是指这个id
  const selectRoleId = ref('')
  const confirm = async () => {
    if (!selectRoleId.value) {
      global.$message({ message: '请选择角色', type: 'warning' })
      return
    }
    let parm = {
      roleId: selectRoleId.value,
      userId: selecUserId.value
    }
    console.log(parm)
    let res = await assingRoleSaveApi(parm)
    if (res && res.code == 200) {
      global.$message({ message: '分配成功', type: 'success' })
      //关闭弹框
      onClose()
    }
  }
  const show = async (name: string, userId: string | number) => {
    selecUserId.value = userId
    selectRoleId.value = ''
    //查询该用户原来的角色id，这个是用来回显用户原来的角色
    let res = await getRoleIdApi(userId)
    if (res && res.data) {
      selectRoleId.value = res.data.roleId
    }
    dialog.height=290
    //设置弹框标题
    dialog.title = '为【' + name + '】分配角色'
    onShow()
  }
  //角色列表查询参数
  const parms = reactive<AssignRoleListParm>({
    currentPage: 1,
    pageSize: 5,
    userId: getUserId() || '',
    total: 0
  })
  //角色列表数据
  const roleList = reactive({
    list: []
  })
  // 获取角色列表的数据
  const getRoleList = async () => {
    let res = await getRoleListApi(parms)
    if (res && res.code == 200) {
      roleList.list = res.data.records
      parms.total = res.data.total
    }
  }
  // 改变页容量
  const currentChange = (page: number) => {
    parms.currentPage = page
    getRoleList()
  }
  // 改变页数
  const sizeChange = (size: number) => {
    parms.pageSize = size
    getRoleList()
  }
  //单选按钮点击事件
  const getSlectRole = (row: any) => {
    console.log(row)
    //设置选中的角色id
    selectRoleId.value = row.id
  }
  onMounted(() => {
    nextTick(() => {
      // tableHeight.value = window.innerHeight - 520
      tableHeight.value = 240
    })
    getRoleList()
  })
  return {
    confirm,
    show,
    roleList,
    parms,
    currentChange,
    sizeChange,
    tableHeight,
    selectRoleId,
    getSlectRole
  }
}
